package com.kevin.Code.Math;

import java.lang.reflect.Array;
import java.util.Arrays;

/**
 * @author Vinlee Xiao
 * @Classname AddBinary
 * @Description Leetcode 67 二进制求和 简单
 * @Date 2021/10/29 9:45
 * @Version 1.0
 */
public class AddBinary {
    public static void main(String[] args) {
        AddBinary addBinary = new AddBinary();
        String s = addBinary.addBinary("110010", "10111");
        System.out.println(s);
    }

    /**
     * @param a
     * @param b
     * @return
     */
    public String addBinary(String a, String b) {

        char[] a1 = a.toCharArray();
        char[] b1 = b.toCharArray();

        int len1 = a1.length;
        int len2 = b1.length;

        char[] res;

        if (len1 < len2) {
            res = Arrays.copyOfRange(a1, 0, a1.length);
            a1 = Arrays.copyOfRange(b1, 0, b1.length);
            b1 = Arrays.copyOfRange(res, 0, res.length);
        }


        //表示进位
        int carry = 0;
        int maxLen = a1.length;
        int minLen = b1.length;

        for (int i = 0; i < minLen; i++) {

            int ch1 = a1[maxLen - 1 - i] - '0';
            int ch2 = b1[minLen - 1 - i] - '0';
            int tmp = ch1 + ch2 + carry;
            a1[maxLen - 1 - i] = (char) (tmp % 2 + '0');
            carry = tmp / 2;
        }

//        System.out.println();
        if (carry == 1) {
            for (int i = minLen; i < maxLen; i++) {

                int reminder = a1[maxLen - i - 1] - '0' + carry;
                a1[maxLen - i - 1] = (char) (reminder % 2 + '0');
                carry = (reminder) / 2;

                if (carry == 0) {
                    break;
                }
            }
        }

//        System.out.println(carry);

        String s1 = new String(a1);
        if (carry == 1) {
            StringBuffer buffer = new StringBuffer();
            char ch = (char) (carry + '0');
            buffer.append(ch);

            buffer.append(s1);
            return buffer.toString();
        }


        return s1;
    }


}
